// Page2.cpp : implementation file
//

#include "stdafx.h"
#include "Property5.h"
#include "Page2.h"
#include "mwrf32.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

using namespace std;
/////////////////////////////////////////////////////////////////////////////
// CPage2 dialog

typedef vector<string> CBlock;

typedef struct CCard
{
	CCard();
	CCard(string strUid);
	string UID;
	map<string,CBlock> MCard;
	int count;
	string strdata;
}CCard;
CCard::CCard()
{
}
CCard::CCard(string strUid)
{
	UID=strUid;
	count=0;
}

typedef vector<CCard> CCards;


unsigned char g_data[256];
vector<string> g_strdata; 

CCards g_Cards;
CCard g_Card;
string g_str;
CString g_cdata;
vector<int> g_vcount;

struct compareuid : public binary_function <CCard ,CCard ,bool> 
{ 
	bool operator () (CCard  lhs, CCard  rhs) 
	{ 
		return lhs.UID < rhs.UID; 
	} 

};

struct comparecount : public binary_function <CCard ,CCard ,bool> 
{ 
	bool operator () (CCard  lhs, CCard  rhs) 
	{ 
		return lhs.count < rhs.count; 
	} 

};
struct comparestrdata : public binary_function <CCard ,CCard ,bool> 
{ 
	bool operator () (CCard  lhs, CCard  rhs) 
	{ 
		return lhs.strdata < rhs.strdata; 
	} 

};
void readCount() 
{
	
	std::ifstream ifs("count.dat");   
	g_vcount.clear();
	std::copy(std::istream_iterator<int>(ifs),std::istream_iterator<int>(),std::back_inserter(g_vcount));

	if (g_vcount.size()==0 )
	{
		return ;
	}

	if (g_vcount.size()!= g_Cards.size())
	{
		::MessageBox(NULL,"size Failed!",NULL,NULL);
		return ;
	}
	
	CCards::iterator it = g_Cards.begin();
	vector<int>::iterator itcount=g_vcount.begin();
	
	for (;it != g_Cards.end();it++)
	{		
			it->count = *itcount;
			itcount++;
		
	}

	ifs.close();
	
}
void writeCount()
{
	g_vcount.clear();

	CCards::iterator it = g_Cards.begin();

	for (;it != g_Cards.end();it++)
	{
		g_vcount.push_back(it->count);
	}


	std::ofstream file("count.dat");
	std::copy(g_vcount.begin(),g_vcount.end(),std::ostream_iterator<int>(file," "));

	file.close();
	
}


void writeData()
{
	std::ofstream file("data.txt");
	std::copy(g_strdata.begin(),g_strdata.end(),std::ostream_iterator<string>(file," "));
	writeCount();

	file.close();

}

void readdata() 
{

	std::ifstream ifs("data.txt");   
	g_Cards.clear();
	g_strdata.clear();
	std::copy(std::istream_iterator<string>(ifs),std::istream_iterator<string>(),std::back_inserter(g_strdata));

	ifs.close();

	
	
}



void Init(string str)
{

	g_Card.count=0;
	g_Card.strdata =str;
	g_Card.UID=str.substr(0,16);
	CBlock blocks;
	for (int i=0;i<16;i++)
	{
		blocks.push_back(str.substr(i,i+8));
	}
	
	g_Card.MCard.insert(make_pair(str.substr(0,16),blocks));

	g_Cards.push_back(g_Card);
	
}

void InitCard()
{
	for_each(g_strdata.begin(),g_strdata.end(),Init);
	readCount();
}


CPage2::CPage2(CWnd* pParent /*=NULL*/)
	: CDialog(CPage2::IDD, pParent)
{
	//{{AFX_DATA_INIT(CPage2)
	m_Block00 = 0;
	m_Block02 = 0;
	m_Block15 = 1;
	m_Data = _T("");
	m_strUid = _T("");
	m_strBlockData = _T("");
	m_iBlock = 0;
	//}}AFX_DATA_INIT
}


void CPage2::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CPage2)
	DDX_Control(pDX, IDC_LIST_DATA, m_ctrldata);
	DDX_Control(pDX, IDC_UIDS, m_CtrlUid);
	DDX_Control(pDX, IDC_RWSTATUS, m_Rwstatus);
	DDX_Check(pDX, IDC_CHECK_BLOCK00, m_Block00);
	DDX_Check(pDX, IDC_CHECK_BLOCK02, m_Block02);
	DDX_Check(pDX, IDC_CHECKBLOCK15, m_Block15);
	DDX_Text(pDX, IDC_EDIT_UID, m_strUid);
	DDX_Text(pDX, IDC_EDIT1_BLOCKDATA, m_strBlockData);
	DDV_MaxChars(pDX, m_strBlockData, 8);
	DDX_Text(pDX, IDC_EDIT_BLOCK, m_iBlock);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CPage2, CDialog)
	//{{AFX_MSG_MAP(CPage2)
	ON_BN_CLICKED(IDC_READ, OnRead)
	ON_BN_CLICKED(IDC_COPY, OnCopy)
	ON_NOTIFY(NM_CLICK, IDC_UIDS, OnClickUids)
	ON_NOTIFY(NM_CLICK, IDC_LIST_DATA, OnClickListData)
	ON_BN_CLICKED(IDC_LOAD, OnLoad)
	ON_MESSAGE(WM_MY_MESSAGE,OnMyMessage) 
	ON_BN_CLICKED(IDC_DELETE, OnDelete)
	ON_BN_CLICKED(IDC_BUTTON_DELETEALL, OnButtonDeleteall)
	ON_BN_CLICKED(IDC_SAVE, OnSave)
	ON_BN_CLICKED(IDC_BUTTON_REFRESH, OnButtonRefresh)
	ON_BN_CLICKED(IDC_BTN_EXPORT, OnBtnExport)
	ON_BN_CLICKED(IDC_BTN_IMPORT, OnBtnImport)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CPage2 message handlers
void CPage2::OnRead() 
{
	// TODO: Add your control notification handler code here
     UpdateData(TRUE);
	
    __int16 st;
	unsigned char _Rwstatus[30];
	memset(_Rwstatus,0,30);
	unsigned char data[256];
	unsigned char recv[256];
	memset(data,0,256);	
	//unsigned char _Status[30];
	//rf_get_status(icdev,_Status);
  	st = rf_select_protocal(icdev,2);
	if(st)
	{
		m_Rwstatus.SetWindowText("Communicate failed !");
		return;
	}
    st = rf_reset(icdev,5);

    st = rf_config_mode(icdev,0,0 );
	if(st)
	{
		m_Rwstatus.SetWindowText("set config mode failed !");
		return;
	}
       st = rf_icode_config(icdev,0,0);
	if(st)
	{
		m_Rwstatus.SetWindowText("read config modefailed !");
		return;
	}
        //unsigned char recv[256];
	  st = rf_icode_get_info(icdev,recv);
	if(st)
	{
		m_Rwstatus.SetWindowText("get info failed !");
		return;
	}
   	 st = rf_icode_set_port(icdev,0x00);
		if(st)
	{
		m_Rwstatus.SetWindowText("set port failed !");
		return;
	}
	  unsigned char portbyte;
      st = rf_icode_get_port(icdev,&portbyte);
     if(st)
	{
		m_Rwstatus.SetWindowText("get port failed !");
		return;
	}

       //unsigned char recv[256];
       memset(recv,0,256);
     st = rf_icode_anticoll(icdev,0,0,recv);
	if(st)
	{
		m_Rwstatus.SetWindowText("anticoll failed !");
		return;
	}
    	int ntimeslot = rf_get_timeslots();
		rf_reset_quiet_bit(icdev);
     	unsigned char temp[256];
	    memset(temp,0,256);
		//st = rf_read(icdev,Sec*4,data);
		st = rf_icode_read(icdev,0,16,data);
		//st = rf_icode_read_unselected(icdev,0,0,0,1,data);

		if(st) 
		{
			m_Rwstatus.SetWindowText("Read failed !");
			return;
		}
         //a_hex((char*)temp,data,16);
		hex_a(data,(char*)temp,65);
		memcpy(g_data,temp,130);
		
	
		CString tmp_data;
		string tmp_str;
		tmp_data.Format("%s",temp);
		tmp_str = tmp_data.GetBuffer(0);
		if ("00" != tmp_str.substr(0,2))
		{
			m_Rwstatus.SetWindowText("No card is detected on reader !");
			return;
		}

		CString tempcstr;
		string tempstr;
		
		
		
		
		
		tempcstr.Format("%s",g_data);
		tempstr = tempcstr.GetBuffer(0);
		
		g_str =tempstr.substr(2,128);
	

		g_cdata = g_str.c_str();

	    // MessageBox(g_cdata);

	
	
		
		m_Rwstatus.SetWindowText("Read Successful!");
		rf_beep(icdev,10);
	
        
    	//rf_exit(icdev);
		ShowData();

// 		::MessageBox(NULL,g_str.c_str(),NULL,NULL);
// 		CString strtemp;
// 		strtemp.Format("%d",g_strdata.size());
// 		::MessageBox(NULL,strtemp,NULL,NULL);

		vector<string>::iterator it = g_strdata.begin();
// 		for (;it!=g_strdata.end();it++)
// 		{
// 			if (*it==g_str)
// 			{
// 				return ;
// 			}
// 		}

		sort(g_Cards.begin(),g_Cards.end(),compareuid());
		pair< vector<CCard>::iterator,vector<CCard>::iterator > itg;


		it=g_strdata.begin();
		for (;it!=g_strdata.end();it++)
		{
			if ((*it).substr(0,16)==g_str.substr(0,16))
			{
				 itg=equal_range(g_Cards.begin(),g_Cards.end(),CCard(g_str.substr(0,16)),compareuid());
				
					if (itg.first==itg.second)
					{
						MessageBox("Find Failed!");
						return;
					}

					if (itg.first->count!=0)
					{
						if (IDYES==MessageBox("Repeat UID!reset count 0 ?","Warning",MB_YESNO))
						{
							vector<string>::iterator it = g_strdata.begin();
							for (;it!=g_strdata.end();it++)
							{
								if ((*it).substr(0,16)==g_str.substr(0,16))
								{
									g_strdata.erase(it);
									break;
								}
							}
							vector<CCard>::iterator itv = g_Cards.begin();
							for (;itv!=g_Cards.end();itv++)
							{
								if ((itv->strdata).substr(0,16) == g_str.substr(0,16))
								{
									g_Cards.erase(itv);
									break;
								}
	}

							g_Card.count = 0;
							g_Card.strdata = g_str;
							g_Card.UID=g_str.substr(0,16);
							g_Cards.push_back(g_Card);
							g_strdata.push_back(g_str);
							Show();
							return;
						}
						else
						{
							vector<string>::iterator it = g_strdata.begin();
							for (;it!=g_strdata.end();it++)
							{
								if ((*it).substr(0,16)==g_str.substr(0,16))
								{
									g_strdata.erase(it);
									break;
								}
							}
							vector<CCard>::iterator itv = g_Cards.begin();
							for (;itv!=g_Cards.end();itv++)
							{
								if (itv->strdata.substr(0,16) == g_str.substr(0,16))
								{
									g_Card.count = itg.first->count;
									g_Cards.erase(itv);
									break;
								}
							}

							
							g_Card.strdata = g_str;
							g_Card.UID=g_str.substr(0,16);
							g_Cards.push_back(g_Card);
							g_strdata.push_back(g_str);
							Show();
							return;

						}
						
					}
					else
					{
						vector<string>::iterator it = g_strdata.begin();
							for (;it!=g_strdata.end();it++)
							{
								if ((*it).substr(0,16)==g_str.substr(0,16))
								{
									g_strdata.erase(it);
									break;
								}
							}
							vector<CCard>::iterator itv = g_Cards.begin();
							for (;itv!=g_Cards.end();itv++)
							{
								if ((itv->strdata).substr(0,16) == g_str.substr(0,16))
								{
									g_Cards.erase(itv);
									break;
								}
	}

							g_Card.count = 0;
							g_Card.strdata = g_str;
							g_Card.UID=g_str.substr(0,16);
							g_Cards.push_back(g_Card);
							g_strdata.push_back(g_str);
							Show();
						return;
					}
					

				

				
			}
		
		}

		g_Card.count = 0;
		g_Card.strdata = g_str;
		g_Card.UID=g_str.substr(0,16);
		g_Cards.push_back(g_Card);
		g_strdata.push_back(g_str);
		
		
		

		m_CtrlUid.InsertItem(0,"0");
		m_CtrlUid.SetItemText(0,1,g_str.substr(0,16).c_str());

// 		CString strtemp;
// 		strtemp.Format("%d",g_Cards.size());
// 		::MessageBox(NULL,strtemp,NULL,NULL);
// 		::MessageBox(NULL,g_str.c_str(),NULL,NULL);

		
		Show();
	    UpdateData(FALSE);
		//rf_exit(icdev);
	    
		//return;
}

void CPage2::OnCopy() 
{


	// TODO: Add your control notification handler code here
	    UpdateData(TRUE);

		string staa;
	    staa = g_cdata.GetBuffer(128);
	    CString m_Data=staa.c_str();
		__int16 st;
		unsigned char w_temp[130];
        unsigned char w_data[130];
		unsigned char tdata[9];
        unsigned char atemp[5];
	    unsigned char recv[128];

        memset(recv,0,128);
        memset(w_temp,0,130);
 	    memset(w_data,0,sizeof(w_data));
		atemp[5] = 0;

		//CString tempstr;
	
	    //MessageBox(m_Data.GetBuffer(128));
		st = rf_select_protocal(icdev,2);
	if(st)
	{
		m_Rwstatus.SetWindowText("Communicate failed !");
		return;
	}
    st = rf_reset(icdev,5);

    st = rf_config_mode(icdev,0,0 );
	if(st)
	{
		m_Rwstatus.SetWindowText("set config mode failed !");
		return;
	}
       st = rf_icode_config(icdev,0,0);
	if(st)
	{
		m_Rwstatus.SetWindowText("read config modefailed !");
		return;
	}
        //unsigned char recv[256];
	  st = rf_icode_get_info(icdev,recv);
	if(st)
	{
		m_Rwstatus.SetWindowText("get info failed !");
		return;
	}
   	 st = rf_icode_set_port(icdev,0x00);
		if(st)
	{
		m_Rwstatus.SetWindowText("set port failed !");
		return;
	}
	  unsigned char portbyte;
      st = rf_icode_get_port(icdev,&portbyte);
     if(st)
	{
		m_Rwstatus.SetWindowText("get port failed !");
		return;
	}

       //unsigned char recv[256];
       memset(recv,0,256);
     st = rf_icode_anticoll(icdev,0,0,recv);
	if(st)
	{
		m_Rwstatus.SetWindowText("anticoll failed !");
		return;
	}
    	//int ntimeslot = rf_get_timeslots();
		rf_icode_read(icdev,0,1,tdata);

		hex_a(tdata,(char*)atemp,5);

		CString atmp_data;
		string atmp_str;
		atmp_data.Format("%s",atemp);
		atmp_str = atmp_data.GetBuffer(0);
		if ("00" != atmp_str.substr(0,2))
		{
			m_Rwstatus.SetWindowText("No card is detected on reader !");
			return;
		}
		if(m_Block00 == 0&&m_Block02 == 0&&m_Block15 == 0)
		{
           m_Rwstatus.SetWindowText("Select blocks please !");
		   	return;
		}

 		a_hex(m_Data.GetBuffer(128),w_temp,128);		
		g_cdata.ReleaseBuffer();

		__int16 block;
		unsigned	char  time =0xff;
		unsigned char *ptime =&time;
        unsigned char * p =w_temp;
		if(m_Block00 == 1)
		{
            block=0;
	    memcpy(w_data,p,4);
	    w_data[4]=0;
		st = rf_icode_write(icdev,0,block,w_data,ptime,recv);
		 if(st)
		 {
			m_Rwstatus.SetWindowText("Copy failed !");
			return;
		 }
		    block=1;
	        p=p+4;
	    memcpy(w_data,p,4);
	    w_data[4]=0;
		st = rf_icode_write(icdev,0,block,w_data,ptime,recv);
			if(st)
			{
			m_Rwstatus.SetWindowText("Copy failed !");
			return;
			}
		}
 		if(m_Block15 == 1)
 		{
 	    	p=p+12;
            //block=15;
		 for(block=3;block<16;block++)
		 {
 	       memcpy(w_data,p,4);
 	       w_data[4]=0;
		   st = rf_icode_write(icdev,0,block,w_data,ptime,recv);
		   if(st)
		   {
			m_Rwstatus.SetWindowText("Copy failed !");
			return;
		   }
		   p=p+4;
		 }
		}
		if(m_Block02 == 1)
		{
            block=2;
	    	p=p+8;
	    memcpy(w_data,p,4);
	    w_data[4]=0;
		st = rf_icode_write(icdev,0,block,w_data,ptime,recv);
		 if(st)
		 {
			m_Rwstatus.SetWindowText("Copy failed !");
			return;
		 }
        }
	m_Rwstatus.SetWindowText("Copy Successful !");
	rf_beep(icdev,10);
	
	//UpdateData(FALSE);
	//st = rf_halt(icdev);
	//Write count
	sort(g_Cards.begin(),g_Cards.end(),compareuid());
	pair< vector <CCard>::iterator, vector <CCard>::iterator >  it;
		  
		  string tt;
		  tt=g_cdata.GetBuffer(0);
		  tt=tt.substr(0,16);
		  sort(g_Cards.begin(),g_Cards.end(),compareuid());
		  it = equal_range(g_Cards.begin(),g_Cards.end(),CCard(tt),compareuid());
		  if (it.first==it.second)
		  {
			  MessageBox("Failed!","ERROR");
			  return;
		  }
		  
		  it.first->count +=1;
		
		 CString tempcstr;
		int i=0;



		CCards::iterator ita = g_Cards.begin();
		m_CtrlUid.DeleteAllItems();
		for (;ita != g_Cards.end();ita++)
		{
			tempcstr.Format("%d",ita->count);
			m_CtrlUid.InsertItem(i,tempcstr.GetBuffer(0));
			m_CtrlUid.SetItemText(i++,1,(ita->UID).c_str());
		}
		
		UpdateData(FALSE);
	
}

void CPage2::OnOK() 
{
	// TODO: Add extra validation here
	CDialog::OnOK();
}

int CPage2::DoModal() 
{
	// TODO: Add your specialized code here and/or call the base class
//	rf_exit(icdev);
	
	return CDialog::DoModal();
}

BOOL CPage2::OnInitDialog()
{
	CDialog::OnInitDialog();


//	m_CtrlUid.SetTextColor(RGB (0, 0, 0));
//	m_CtrlUid.SetTextBkColor(RGB (140, 180, 220));
//	m_CtrlUid.SetBkColor(RGB (140, 180, 220));
//	m_CtrlUid.SetTextColor(RGB (0, 0, 0));
//	m_CtrlUid.SetTextBkColor(RGB (140, 180, 220));
//	m_CtrlUid.SetBkColor(RGB (140, 180, 220));
//   m_CtrlUid.ShowWindow(SW_HIDE);

	m_CtrlUid.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);
    m_CtrlUid.InsertColumn(0,_T("COUNT"),LVCFMT_IMAGE|LVCFMT_LEFT);
	m_CtrlUid.InsertColumn(1,_T("UID"),LVCFMT_IMAGE|LVCFMT_LEFT);
	
	m_CtrlUid.SetColumnWidth(0, 60);
	m_CtrlUid.SetColumnWidth(1, 180);


	CDialog::OnInitDialog();
//	m_ctrldata.SetTextColor(RGB (0, 0, 0));
//	m_ctrldata.SetTextBkColor(RGB (140, 180, 220));
//	m_ctrldata.SetBkColor(RGB (140, 180, 220));
//	m_ctrldata.SetTextColor(RGB (0, 0, 0));
//	m_ctrldata.SetTextBkColor(RGB (140, 180, 220));
//	m_ctrldata.SetBkColor(RGB (140, 180, 220));

	
	m_ctrldata.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);
    m_ctrldata.InsertColumn(0,_T("BLOCK"),LVCFMT_IMAGE|LVCFMT_LEFT);
	m_ctrldata.InsertColumn(1,_T("DATA"),LVCFMT_IMAGE|LVCFMT_LEFT);
	m_ctrldata.SetColumnWidth(0, 60);
	m_ctrldata.SetColumnWidth(1, 180);

	readdata();
	InitCard();
	Show();
	rf_reset(icdev,5);

		__int8 comn;
		rf_exit(icdev);
		for(comn=0;comn<8;comn++)
		{
			icdev = rf_init(comn,115200);
// 			CString astr;
// 			astr.Format("%d",icdev);
//              MessageBox(astr);
			if((int)icdev>=0)
			{
              break;
			}
			
		}
		
		UpdateData(false);
		
		
		
		
		
		return TRUE;  // return TRUE  unless you set the focus to a control
}




void CPage2::Show()
{
	UpdateData(true);
 	m_CtrlUid.DeleteAllItems();
//	readdata();
//	InitCard();

	int i=0;
	CString tempcstr;
	
	
	CCards::iterator it = g_Cards.begin();

	sort(g_Cards.begin(),g_Cards.end(),comparecount());
	
	for (;it != g_Cards.end();it++)
	{
		tempcstr.Format("%d",it->count);
		m_CtrlUid.InsertItem(i,tempcstr.GetBuffer(0));
		m_CtrlUid.SetItemText(i++,1,(it->UID).c_str());
 	}

	UpdateData(false);

	
	

}

    

void CPage2::OnClickUids(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	int i = m_CtrlUid.GetSelectionMark();
	m_strUid = m_CtrlUid.GetItemText(i,1);

	sort(g_Cards.begin(),g_Cards.end(),compareuid());
	pair< vector <CCard>::iterator, vector <CCard>::iterator >  it;

	it = equal_range(g_Cards.begin(),g_Cards.end(),CCard(m_strUid.GetBuffer(0)),compareuid());
	if (it.first==it.second)
	{
		MessageBox("Failed!");
		return ;
	}
	g_str=it.first->strdata;
	g_cdata=g_str.c_str();

	//MessageBox(g_cdata);
	
	ShowData();


	UpdateData(false);
	
	*pResult = 0;
}

void CPage2::OnClickListData(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here

	int nId;
	CString str;
	POSITION pos=m_ctrldata.GetFirstSelectedItemPosition();
	nId=(int)m_ctrldata.GetNextSelectedItem(pos);
    

	int i = m_ctrldata.GetSelectionMark();
	m_iBlock = nId;
	m_strBlockData = m_ctrldata.GetItemText(i,1);	
	UpdateData(false);
	
	*pResult = 0;
}

void CPage2::ShowData()
{


	CString tempcstr;	
	m_ctrldata.DeleteAllItems();
	
	for (int i=0;i<16;i++)
	{
		tempcstr.Format("%d",i);
		m_ctrldata.InsertItem(i,tempcstr);
		m_ctrldata.SetItemText(i,1,g_str.substr(i*8,8).c_str());
	}

}

void CPage2::DeleteRepeat()
{
//	readdata();
	sort(g_strdata.begin(),g_strdata.end());
	g_strdata.erase(unique(g_strdata.begin(),g_strdata.end()),g_strdata.end());
//	writeData();
}

void CPage2::OnLoad() 
{
	// TODO: Add your control notification handler code here
	InputDlg.SetPhwnd(m_hWnd);
	InputDlg.DoModal();
	
}

LRESULT CPage2::OnMyMessage()
{
	g_str=InputDlg.m_inputData.GetBuffer(0);
	g_strdata.push_back(g_str.c_str());
    g_Card.UID = g_str.substr(0,16);
	g_Card.strdata=g_str;
	g_Card.count=0;

	g_Cards.push_back(g_Card);

	g_cdata = g_str.c_str();
		
    //MessageBox(g_cdata);
    Show();
	ShowData();
	return 1;
}

void CPage2::OnDelete() 
{
	// TODO: Add your control notification handler code here
	if (IDYES==MessageBox("Are you sure delete data?","Warning",MB_YESNO))
	{

	CString str;

	POSITION pos=m_CtrlUid.GetFirstSelectedItemPosition();

	if (pos == NULL)
	{
		MessageBox("Please select one UID!","Warning");
		return ;
	}

	int i = m_CtrlUid.GetSelectionMark();
	str = m_CtrlUid.GetItemText(i,1);


	sort(g_Cards.begin(),g_Cards.end(),compareuid());
	pair< vector <CCard>::iterator, vector <CCard>::iterator >  it;

	it = equal_range(g_Cards.begin(),g_Cards.end(),CCard(str.GetBuffer(0)),compareuid());
	if (it.first==it.second)
	{
		MessageBox("Failed!");
		return ;
	}

	vector<string>::iterator itstr =g_strdata.begin();
	for (;itstr!=g_strdata.end();itstr++)
	{	
		if ((it.first->UID)==(*itstr).substr(0,16))
		{
			g_strdata.erase(itstr);
			g_Cards.erase(it.first);		
			break;
		}
	}
	
	
	

	Show();
	
}	
}

void CPage2::OnButtonDeleteall() 
{
	// TODO: Add your control notification handler code here
	if (IDYES==MessageBox("Are you sure delete all data?","Warning",MB_YESNO))
	{
		g_strdata.clear();
		g_Cards.clear();
		g_vcount.clear();

		Show();
	}
	

	
}

void CPage2::OnSave() 
{
	// TODO: Add your control notification handler code here
	UpdateData(true);
	 if (m_strBlockData=="")
	 {
		 MessageBox("There are not data");
		 return;
	 }
	 
	 if (8!=m_strBlockData.GetLength())
	 {
		 MessageBox("Data Length wrong!");
		 return;
	 }
	 
	 
	 
	 m_ctrldata.SetItemText(m_iBlock,1,m_strBlockData);
	 
	 CString cstr;
	 for (int i=0;i<16;i++)
	 {
		 cstr += m_ctrldata.GetItemText(i,1);		
	 }
	 g_cdata = cstr;
	 
	 vector<string>::iterator it = g_strdata.begin();
	 for (;it!=g_strdata.end();it++)
	 {
		 if ((*it).substr(0,16)==g_str.substr(0,16))
		 {
			 g_strdata.erase(it);
			 break;
		 }
	 }
	 vector<CCard>::iterator itv = g_Cards.begin();
	 for (;itv!=g_Cards.end();itv++)
	 {
		 if (itv->strdata.substr(0,16) == g_str.substr(0,16))
		 {
			 g_Cards.erase(itv);
			 break;
		 }
	 }
	 g_strdata.push_back(cstr.GetBuffer(0));
	 
	 
	 g_str=cstr.GetBuffer(0);
	 g_Card.count=0;
	 g_Card.UID=g_str.substr(0,16);
	 g_Card.strdata=g_str;
	 g_Cards.push_back(g_Card);
	 g_vcount.push_back(0);
	 
	 
	 Show();
	 
	 
	UpdateData(false);
	
}

void CPage2::OnButtonRefresh() 
{
	// TODO: Add your control notification handler code here

	sort(g_Cards.begin(),g_Cards.end(),comparecount());
	Show();
	UpdateData(false);


	
	
}

void CPage2::OnBtnExport() 
{
	// TODO: Add your control notification handler code here
	string exename;
	exename = AfxGetApp()->m_pszExeName;

	CString s_filename;
	char data[128];
	CString s_data;
	string  strdata;
	GetModuleFileName(NULL,data,128);
	strdata=data;
	strdata = strdata.substr(0,strdata.length()-exename.length()-4);
	strdata = strdata + "data.txt";
	s_data = strdata.c_str();

	char pathB[256];
	GetCurrentDirectory(256,pathB);

	CString spath;
	string strpath;
	writeData();

	CFileDialog dlg(FALSE,".txt","data",OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,"Chart Files (*.txt)|*.txt|Worksheet Files (*.txt)|*.txt|Data Files (*.txt;*.txt)|*.txt; *.txt|All Files (*.*)|*.*||",NULL);
	if(IDOK == dlg.DoModal())
	{
		s_filename = dlg.GetFileName();
		//CopyFile((LPCSTR)s_data,(LPCSTR)s_filename,FALSE);
		CopyFile((LPCTSTR)s_data,(LPCTSTR)s_filename,FALSE);
		strdata=pathB;
		strdata = strdata +"\\" + "count.dat";
		s_data = strdata.c_str();
		
		strpath = s_filename.GetBuffer(0);
		strpath = strpath.substr(0,strpath.length()-4);
		strpath = strpath + ".dat";
		spath = strpath.c_str();		

		CopyFile((LPCTSTR)s_data,(LPCTSTR)spath,FALSE);
		SetCurrentDirectory(pathB);	
	}



}

void CPage2::OnBtnImport() 
{
	// TODO: Add your control notification handler code here

	string exename;
	exename = AfxGetApp()->m_pszExeName;
	
	CString s_filename;
	char data[128];
	CString s_data;
	string  strdata;
	GetModuleFileName(NULL,data,128);
	strdata=data;
	strdata = strdata.substr(0,strdata.length()-exename.length()-4);
	strdata = strdata + "data.txt";
	s_data = strdata.c_str();

	char pathB[256];
	GetCurrentDirectory(256,pathB);
	

	CString spath;
	string strpath;

	CFileDialog dlg(TRUE,"C:\\","data",OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,"Chart Files (*.txt)|*.txt|Worksheet Files (*.txt)|*.txt|Data Files (*.txt;*.txt)|*.txt; *.txt|All Files (*.*)|*.*||",NULL);
	if(IDOK == dlg.DoModal())
	{
		s_filename = dlg.GetFileName();
        //CopyFile((LPCSTR)s_filename,(LPCSTR)s_data,FALSE);
		CopyFile((LPCTSTR)s_filename,(LPCTSTR)s_data,FALSE);

		strdata=pathB;
		strdata = strdata + "\\" + "count.dat";
		s_data = strdata.c_str();

		spath = dlg.GetPathName();
		strpath = spath.GetBuffer(0);
		strpath = strpath.substr(0,strpath.length()-4);
		strpath = strpath + ".dat";
		spath = strpath.c_str();
		MessageBox(spath);
		MessageBox(s_data);

		CopyFile((LPCTSTR)spath,(LPCTSTR)s_data,FALSE);

		SetCurrentDirectory(pathB);		

	    readdata();
	    InitCard();
	    Show();
	}


	
}
